<template>
  <!-- 充值查询 -->
  <div class="user_recharge_query">
    <el-form :inline="true" :model="elform" class="demo-form-inline1">
      <el-form-item label="部门:">
        <el-select v-model="departmentGuid" placeholder="请选择" size="mini" clearable>
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户姓名:">
        <el-input placeholder="用户姓名" v-model="userName" style="width: 120px" clearable size="mini"></el-input>
      </el-form-item>
      <!-- <el-form-item label="用户编号:">
        <el-input
          placeholder="用户编号"
          v-model="userNumber"
          style="width: 120px"
          clearable
          size="mini"
        ></el-input>
      </el-form-item>-->
      <el-form-item label="卡号:">
        <el-input placeholder="卡号" v-model="cardNumber" style="width: 120px" clearable size="mini"></el-input>
      </el-form-item>
      <el-form-item label="领取情况:">
        <el-select
          v-model="adjustState"
          placeholder="请选择"
          size="mini"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="充值方式:">
        <el-select
          v-model="rechargeMode"
          placeholder="请选择"
          size="mini"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in fiveOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="充值类型:">
        <el-select
          v-model="deductionTypeId"
          placeholder="请选择"
          size="mini"
          style="width: 120px"
          clearable
        >
          <el-option
            v-for="item in deductionlist"
            :key="item.pkTypeId"
            :label="item.typeName"
            :value="item.pkTypeId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="钱包:" prop="walletNo">
        <el-select
          v-model="waterWalletNo"
          placeholder="请选择"
          size="mini"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in paylist"
            :key="item.walletNo"
            :label="item.walletName"
            :value="item.walletNo"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期:">
        <el-date-picker
          v-model="datetime[0]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[0]"
          value-format="HH:mm:ss"
          placeholder="开始时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="结束日期:">
        <el-date-picker
          v-model="datetime[1]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[1]"
          value-format="HH:mm:ss"
          placeholder="结束时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="gosearch()" size="mini">查询</el-button>
        <el-button type="primary" @click="exportInfo()" size="mini">导出</el-button>
        <el-button type="primary" @click="exportInfo('print')" size="mini">打印</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableinformation"
      style="width: 100%"
      border="border"
      :header-cell-style="headFirst"
      :cell-style="
        detailsTotal ? (res) => headFirst_col(res, tableinformation) : () => {}
      "
      highlight-current-row
      stripe
      v-loading="loading"
    >
      <el-table-column prop="departmentName" label="部门名称" min-width="120px"></el-table-column>
      <el-table-column prop="userName" label="姓名"></el-table-column>
      <el-table-column prop="cardNumber" label="卡号" min-width="100px"></el-table-column>
      <el-table-column prop="walletName" label="充值钱包" min-width="110px"></el-table-column>
      <el-table-column prop="rechargeMode" label="充值方式" min-width="100px">
        <template slot-scope="scope">
          <div>{{ scope.row.rechargeMode | filtermode }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="rechargeTypeName" label="充值类型" min-width="110px"></el-table-column>
      <el-table-column prop="rechargeAmount" label="充值金额(元)" min-width="100px">
        <template slot-scope="scope">
          <div>{{ scope.row.rechargeAmount | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="充值后金额(元)" min-width="94px">
        <template slot-scope="scope">
          <div v-if="scope.row.rechargeState != 1">—</div>
          <div v-else>{{ scope.row.balance | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="rechargeSerial" label="充值流水号"></el-table-column>
      <el-table-column prop="paymentTime" label="充值时间" min-width="150px"></el-table-column>
      <!-- <el-table-column prop="syncState" label="同步状态">
        <template slot-scope="scope">
          <div>{{ scope.row.syncState | filtersync }}</div>
        </template>
      </el-table-column>-->
      <el-table-column prop="rechargeState" label="是否领取">
        <template slot-scope="scope">
          <div>{{ scope.row.rechargeState | filterstate }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="successTime" label="领取时间" min-width="150px"></el-table-column>
      <el-table-column prop="syncState" label="同步状态" v-if="isoneCardSolutionUse">
        <template slot-scope="scope">
          <div>{{ scope.row.syncState | filtersync }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="syncTime" label="同步时间" min-width="150px" v-if="isoneCardSolutionUse"></el-table-column>
      <el-table-column label="操作" aling="center" v-if="userType == '1'" min-width="240px">
        <template
          slot-scope="scope"
          v-if="!(detailsTotal && scope.$index == tableinformation.length - 1)"
        >
          <el-button type="text" size="mini" @click="setCar(scope.row)">重新下发</el-button>
          <el-button type="text" size="mini" @click="markSuccess(scope.row)">标志为已领取</el-button>
          <el-button type="text" size="mini" @click="sendNewCard(scope.row)">重发到新卡</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChangepage"
        @current-change="handleCurrentChangepage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :current-page="currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="recordCount"
      ></el-pagination>
    </div>

    <el-dialog
      title="重新下发"
      :visible.sync="subscribe"
      width="500px"
      center
      :close-on-click-modal="false"
      :before-close="closeDialog"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        style="margin-left: 0%"
      >
        <el-form-item label="当前最大流水号:" prop="maxSerial">
          <el-col :span="16">
            <el-input size="mini" v-model="ruleForm.maxSerial" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="流水号:" prop="newSerial">
          <el-col :span="16">
            <el-input size="mini" v-model="ruleForm.newSerial"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="subscribeAdd(row)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isoneCardSolutionUse: false,
      elform: {},
      // 弹框显示
      operationId: 1,
      subscribe: false,
      loading: false,
      ruleForm: {
        // 流水号
        newSerial: '',
        maxSerial: ''
      },
      // 充值类型
      deductionTypeId: '',
      deductionlist: [],
      rules: {},
      // 表格加载中
      loading: false,
      /** 分页数据 */
      pageNum: 1,
      pageSize: 20,
      currentPage: 0,
      recordCount: 0,
      // 接口参数
      messageType: 0,
      sortName: '',
      // 当前登录号的id
      administrator: '',
      // 单位id
      changeschoolid: '',
      // 合计数据
      detailsTotal: null,
      // 导出数据
      agentlistout: [],
      // 减款数据
      tableinformation: [],
      /**搜索条件 */
      // 部门列表
      departmentoptions: [],
      // 当前部门
      departmentGuid: '',
      // 用户名
      userName: '',
      // 用户编号
      userNumber: '',
      // 卡号
      cardNumber: '',
      // 状态
      adjustState: '',
      // 时间
      value1: '',
      value2: '',
      datetime: '',
      time: '',

      options: [
        {
          value: 0,
          label: '未领取'
        },
        {
          value: 1,
          label: '已领取'
        },
        {
          value: 2,
          label: '领取失败'
        }
      ],
      // 充值方式
      rechargeMode: '',
      fiveOptions: [
        { value: 0, label: '卡务中心充值' },
        { value: 10, label: '发卡预存款' },
        { value: 3, label: '充值机充值' },
        { value: 1, label: '平台无卡充值' },
        { value: 2, label: '支付宝充值' },
        { value: 6, label: '微信充值' },
        { value: 5, label: '第三方充值' }
      ],
      searchInfo: {},
      // 钱包
      paylist: [],
      waterWalletNo: ''
    }
  },
  filters: {
    filtermode: function(mode) {
      // let str = Number(mode);
      let obj = {
        0: '卡务中心充值',
        1: '平台无卡充值',
        2: '支付宝充值',
        3: '充值机充值',
        4: '合并',
        5: '第三方充值',
        6: '微信充值',
        8: '补卡',
        10: '预存款'
      }
      return obj[mode]
    },
    filterstate: function(state) {
      if (state == 1) {
        return '√'
      } else if (state == 0) {
        return '×'
      }
    },
    filtersync: function(sync) {
      if (sync == 1) {
        return '已同步'
      } else if (sync == 0) {
        return '未同步'
      }
    }
  },
  created() {
    this.changeschoolid = this.$store.state.user.changeschoolid
    this.administrator = sessionStorage.getItem('administrator')
    // 账号类型
    this.userType = sessionStorage.getItem('userType')
    // 初始化时间
    this.datetime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
    // 获取部门列表
    this.departmentselectlist()
    // 获取无卡充值类型
    this.getConType()
    this.getunitconfiguration()

    // 获取钱包
    this.getPayNumber()
  },
  methods: {
    // 获取钱包
    getPayNumber() {
      this.paylist = []
      this.$http({
        url: this.$http.adornUrl('/unit/unit-wallet-info-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          data.messageContent.map(item => {
            let walletType = item.walletType
            // 所有的钱包
            if (walletType != 1) {
              this.paylist.push(item)
            }
          })
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: 'error'
          })
        }
      })
    },

    //单位配置信息
    getunitconfiguration() {
      this.$http({
        url: this.$http.adornUrl('/manager/unit-config'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid,
            userGuid: this.administrator
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.isoneCardSolutionUse =
            data.messageContent.oneCardSolutionUse == 1
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },

    // 获取无卡充值类型
    getConType() {
      this.$http({
        url: this.$http.adornUrl('/unit/recharge-type-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.deductionlist = data.messageContent
          if (this.deductionlist.length != 0) {
            this.ruleForm.deductionTypeId = this.deductionlist[0].pkTypeId
          }
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: 'error'
          })
        }
      })
    },

    // 获取部门列表
    departmentselectlist() {
      this.departmentoptions = []
      this.$http({
        url: this.$http.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent == null ? [] : data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentoptions.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 取消重新下发弹窗
    closeDialog() {
      this.$refs['ruleForm'].resetFields()
      this.subscribe = false
    },
    //  获取最大流水号
    getMaxS(row) {
      this.$http({
        url: this.$http.adornUrl('/card/card-recharge-max-serial-search'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            rechargeGuid: row.rechargeGuid,
            unitGuid: this.changeschoolid
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        if (data.messageCode === 200) {
          this.ruleForm.maxSerial = data.messageContent
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 重新下发
    setCar(row, cid) {
      this.row = row
      this.subscribe = true
      this.operationId = cid
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields()
      })
      this.getMaxS(row)
    },
    // 重新下发
    subscribeAdd(row) {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/card/card-handle-recharge'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                newSerial: this.ruleForm.newSerial,
                rechargeGuid: row.rechargeGuid,
                unitGuid: this.changeschoolid
              },
              messageType: this.messageType
            })
          }).then(({ data }) => {
            if (data.messageCode === 200) {
              this.$message({
                message: '处理成功',
                type: 'success'
              })
              this.subscribe = false
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        }
      })
    },
    // 下发新卡
    sendNewCard(row) {
      this.$http({
        url: this.$http.adornUrl('/card/card-handle-recharge-change'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            rechargeGuid: row.rechargeGuid,
            unitGuid: this.changeschoolid
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        if (data.messageCode === 200) {
          this.$message({
            message: '已成功重发至新卡中',
            type: 'success'
          })
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 标志领取
    markSuccess(row) {
      this.$http({
        url: this.$http.adornUrl('/card/card-handle-recharge-success'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            rechargeGuid: row.rechargeGuid,
            unitGuid: this.changeschoolid
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        if (data.messageCode === 200) {
          this.$message({
            message: '已标志为已领取',
            type: 'success'
          })
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    //查询
    async gosearch() {
      this.pageNum = 1
      this.searchInfo = {
        cardNumber: this.cardNumber,
        operatorGuid: this.administrator,
        unitGuid: this.changeschoolid,
        userName: this.userName,
        userNumber: this.userNumber,
        adjustState: this.adjustState,
        departmentGuid: this.departmentGuid,
        rechargeMode: this.rechargeMode,
        deductionTypeId: this.deductionTypeId
      }
      this.searchInfo.walletNo = this.waterWalletNo
      if (this.datetime != null) {
        this.searchInfo.endTime = this.datetime[1] + ' ' + this.time[1]
        this.searchInfo.startTime = this.datetime[0] + ' ' + this.time[0]
      }

      this.detailsTotal = null
      this.detailsTotal = await this.getTotal()
      this.searchinit()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 得到充值记录
    searchinit() {
      this.loading = true
      this.$http({
        url: this.$http.adornUrl('/api/v1/Student/user-recharge-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo,
            sortName: this.sortName
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
          this.tableinformation = data.messageContent.data
          this.pageNum = data.messageContent.pageNum
          this.pageSize = data.messageContent.pageSize
          this.currentPage = data.messageContent.pageNum
          this.recordCount = data.messageContent.recordCount
          if (data.messageContent.data.length != 0) {
            this.tableinformation.push({
              ...this.detailsTotal,
              departmentName: '合计：',
              filtermode: '',
              balance: ''
            })
          } else {
            this.$message({
              message: '查询成功当前暂无数据',
              type: 'success'
            })
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 获取充值合计数据
    getTotal() {
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/api/v1/Student/user-recharge-total'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              resolve(data.messageContent)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 导出数据
    async exportInfo(type) {
      if (this.recordCount == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.getListout()
      if (type == 'print') {
        this.printJS()
      } else {
        this.onexport()
      }
    },
    // 获取所有充值记录
    getListout() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/api/v1/Student/user-recharge-page'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                asc: true,
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo,
                sortName: _this.sortName
              },
              messageType: _this.messageType
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.agentlistout = data.messageContent.data
              if (data.messageContent.data.length != 0) {
                _this.agentlistout.push({
                  ..._this.detailsTotal,
                  departmentName: '合计：',
                  filtermode: '',
                  balance: ''
                })
              }
              _this.agentlistout.map(item => {
                item.rechargeMode = _this.$options.filters.filtermode(
                  item.rechargeMode
                )
                // item.syncState = _this.$options.filters.filtersync(item.syncState);
                item.rechargeState = _this.$options.filters.filterstate(
                  item.rechargeState
                )
                item.balance =
                  item.rechargeState != 1
                    ? '—'
                    : _this.$options.filters.amountyuan(item.balance)
                item.rechargeAmount = _this.$options.filters.amountyuan(
                  item.rechargeAmount
                )
              })
              resolve(_this.agentlistout)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },

    // 拿到表头数据
    getIsPrint() {
      const tHeader = [
        '部门名称',
        '用户姓名',
        '卡号',
        '充值方式',
        '充值金额(元)',
        '充值后金额(元)',
        '充值流水号',
        '充值时间',
        // "同步状态",
        '是否领取成功',
        '领取时间'
      ]
      const filterValArr = [
        'departmentName',
        'userName',
        'cardNumber',
        'rechargeMode',
        'rechargeAmount',
        'balance',
        'rechargeSerial',
        'paymentTime',
        // "syncState",
        'rechargeState',
        'successTime'
      ]

      return { filterValArr, tHeader }
    },
    // 打印
    printJS() {
      let someJSONdata = this.agentlistout
      const title = '无卡充值到账表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getIsPrint()
      filterValArr.map((item, index) => {
        properties.push({
          displayName: tHeader[index],
          field: filterValArr[index]
        })
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 导出数据
    onexport() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        let multiHeader = []
        let merges = []
        const { tHeader, filterValArr } = this.getIsPrint()
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        const filterVal = filterValArr
        const list = this.agentlistout
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader,
          header: tHeader,
          data,
          merges,
          filename: '无卡充值到账表' + this.getimeto()
          // tableheader: "1",
        })
      })
    },
    //分类页
    handleSizeChangepage(val) {
      this.pageSize = val
      this.searchinit()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.searchinit()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-date-editor--datetimerange.el-input,
.el-date-editor--datetimerange.el-input__inner {
  width: 280px;
}

.user_recharge_query {
  padding: 0 10px;
  .demo-form-inline1 {
    margin-top: 10px;
    /deep/.el-form-item {
      margin-bottom: 0px;
    }
  }
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .page {
    // background-color: #f5f5f5;
    padding-bottom: 10px;
    .el-pagination {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
